'''
Cookie
'''
from typing import Union, List, Any

from fastapi import APIRouter, Path, Body, Cookie, Header
from pydantic import BaseModel, EmailStr

router = APIRouter()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float = 10.5
    tax: Union[float, None] = None
    tags: List[str] = []


class UserIn(BaseModel):
    username: str
    password: str
    email: EmailStr
    age: int = 20
    full_name: Union[str, None] = None


class UserOut(BaseModel):
    username: str
    email: EmailStr
    full_name: Union[str, None] = None


class UserInDB(BaseModel):
    username: str
    hashed_password: str
    email: EmailStr
    full_name: Union[str, None] = None


items = {
    "foo": {"name": "Foo", "price": 50.2},
    "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
    "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}


@router.post("/resp/items_1/", response_model=Item, tags=["响应体参数"])
async def create_item(item: Item) -> Any:
    return item


@router.get("/resp/items_2/", response_model=List[Item], tags=["响应体参数"])
async def read_items() -> Any:
    return [
        {"name": "Portal Gun", "price": 42.0},
        {"name": "Plumbus", "price": 32.0},
    ]


@router.post("/resp/user_3/", response_model=UserOut, tags=["响应体参数"])
async def create_user(user: UserIn) -> Any:
    return user


# 默认值不返回，response_model_exclude_unset
@router.get("/resp/read_item_4/{item_id}", response_model_exclude_unset=True, tags=["响应体参数"])
async def read_item(item_id: str):
    return items[item_id]


def fake_password_hasher(raw_password: str):
    return "supersecret" + raw_password


def fake_save_user(user_in: UserIn):
    hashed_password = fake_password_hasher(user_in.password)
    # **user_in.dict() 语法是 Python3.9 新特性，字典展开，并赋值给 user_in_db
    user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
    print("user_in_db 内容是：", user_in_db.dict())
    return user_in_db


@router.post("/resp/user_5/", response_model=UserOut, tags=["响应体参数"])
async def create_user(user_in: UserIn):
    user_saved = fake_save_user(user_in)
    return user_saved


class BaseItem(BaseModel):
    description: str
    type: str


class CarItem(BaseItem):
    type: str = "car"


class PlaneItem(BaseItem):
    type: str = "plane"
    size: int


items = {
    "item1": {"description": "All my friends drive a low rider", "type": "car"},
    "item2": {"description": "Music is my aeroplane, it's my aeroplane", "type": "plane", "size": 5},
}


@router.get("/resp/read_items_6/{item_id}", response_model=Union[PlaneItem, CarItem], tags=["响应体参数"])
async def read_item(item_id: str):
    return items[item_id]
